import app from '../app'
import redisHandle from './redisHandle'

function randomString(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function getRedisID(pID) {
    return app.config.gameName + "session" + pID
}

class SessionHandle {
    session: any
    sessionByID: any
    constructor() {
        this.session = {}
        this.sessionByID = {}
    }

    addSession = async (pID, uID, name) => {
        let sessionKey = randomString(20)
        let redisID = getRedisID(pID)
        let data: any = await redisHandle.get(redisID)
        let session: any
        if (data && data !== "") {
            session = JSON.parse(data)
            if (session.sessionKey) {
                redisHandle.del(app.config.gameName + 'sessionKey' + session.sessionKey)
            }
            session.sessionKey = sessionKey
            redisHandle.set(redisID, JSON.stringify(session))
            redisHandle.set(app.config.gameName + 'sessionKey' + sessionKey, redisID)
            redisHandle.expire(app.config.gameName + 'sessionKey' + sessionKey, 2 * 60 * 60 * 1000);
            redisHandle.expire(redisID, 2 * 60 * 60 * 1000); //设置2个小时自动过期
            return session
        } else {
            session = {
                name: name,
                pID: pID,
                uID: uID,
                score: 0,
                sessionKey: sessionKey
            }

            await redisHandle.set(redisID, JSON.stringify(session))
            await redisHandle.set(app.config.gameName + 'sessionKey' + sessionKey, redisID)
            return session
        }
    }
    getSession = async (sessionKey) => {
        let redisID = await redisHandle.get(app.config.gameName + 'sessionKey' + sessionKey)
        if (redisID) {
            redisHandle.expire(redisID, 2 * 60 * 60 * 1000);
            redisHandle.expire(app.config.gameName + 'sessionKey' + sessionKey, 2 * 60 * 60 * 1000);
            let data: any = await redisHandle.get(redisID)
            data = JSON.parse(data)
            return data
        }
        return null
    }
    updateSession = async (pID, session) => {
        let redisID = getRedisID(pID)
        await redisHandle.set(redisID, JSON.stringify(session))
        await redisHandle.set(app.config.gameName + 'sessionKey' + session.sessionKey, redisID)
    }

    deleteSessionByPID = async (pID) => {
        let redisID = getRedisID(pID)
        let data: any = await redisHandle.get(redisID)
        if (data) {
            data = JSON.parse(data)
            await redisHandle.del(redisID)
            await redisHandle.del(app.config.gameName + 'sessionKey' + data.sessionKey)
        }
    }
}

let sessionHandle = new SessionHandle()
export default sessionHandle